//
//  YLValidatorTransaction.swift
//  Distance
//
//  Created by changhe on 2025/4/27.
//

import Foundation

class YLValidatorTransaction: YLTransactionValidator {
	
    func verifyTransaction(transaction: YLTransactionInfo, receiptData: Data, receiptDataIsJws: Bool, completion: @escaping (Bool, (any Error)?) -> Void) {
        // 准备验证所需参数
        let parameters: [String: Any] = [
            "receipt-data": receiptData.base64EncodedString(),
            "transaction_id": transaction.transactionId,
            "product_id": transaction.productId,
            "order_id": transaction.orderId ?? "",
            "original_transaction_id": transaction.originalTransactionId ?? ""
        ]
        
        // 创建URL请求
        let url = URL(string: "https://your-verify-server.com/api/verify-purchase")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        
        do {
            // 序列化参数
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
            
            // 执行网络请求
            URLSession.shared.dataTask(with: request) { (data, response, error) in
                // 检查是否有错误
                if let error = error {
                    print("[YLPaymentKit]【verify接口验证失败】: \(error.localizedDescription), 订单号: \(transaction.orderId ?? "")")
                    
                    let paymentError = NSError(
                        domain: "YLPaymentErrorDomain",
                        code: -1,
                        userInfo: [
                            NSLocalizedDescriptionKey: "验证请求失败",
                            "details": [
                                "orderId": transaction.orderId ?? "",
                                "transactionId": transaction.transactionId,
                                "timestamp": Date().timeIntervalSince1970
                            ]
                        ]
                    )
                    
                    completion(false, paymentError)
                    return
                }
                
                // 检查响应数据
                guard let data = data else {
                    print("[YLPaymentKit]【verify接口验证失败】: 没有响应数据, 订单号: \(transaction.orderId ?? "")")
                    
                    let paymentError = NSError(
                        domain: "YLPaymentErrorDomain",
                        code: -2,
                        userInfo: [NSLocalizedDescriptionKey: "没有响应数据"]
                    )
                    
                    completion(false, paymentError)
                    return
                }
                
                // 解析响应数据
                do {
                    if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                       let status = json["status"] as? String,
                       status == "success" {
                        
                        print("[YLPaymentKit]【verify接口验证成功】: 订单号: \(transaction.orderId ?? "")")
                        completion(true, nil)
                        
                    } else {
                        // 验证失败
                        print("[YLPaymentKit]【verify接口验证失败】: 验证结果不成功, 订单号: \(transaction.orderId ?? "")")
                        
                        let errorMessage = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
                        
                        let paymentError = NSError(
                            domain: "YLPaymentErrorDomain",
                            code: -3,
                            userInfo: [
                                NSLocalizedDescriptionKey: "验证结果不成功",
                                "response": errorMessage ?? [:]
                            ]
                        )
                        
                        completion(false, paymentError)
                    }
                    
                } catch {
                    // JSON解析错误
                    print("[YLPaymentKit]【verify接口验证失败】: 响应解析失败: \(error.localizedDescription), 订单号: \(transaction.orderId ?? "")")
                    
                    let paymentError = NSError(
                        domain: "YLPaymentErrorDomain",
                        code: -4,
                        userInfo: [NSLocalizedDescriptionKey: "响应解析失败: \(error.localizedDescription)"]
                    )
                    
                    completion(false, paymentError)
                }
            }.resume()
            
        } catch {
            // 参数序列化错误
            print("[YLPaymentKit]【verify接口验证失败】: 参数序列化失败: \(error.localizedDescription), 订单号: \(transaction.orderId ?? "")")
            
            let paymentError = NSError(
                domain: "YLPaymentErrorDomain",
                code: -5,
                userInfo: [NSLocalizedDescriptionKey: "参数序列化失败: \(error.localizedDescription)"]
            )
            
            completion(false, paymentError)
        }
    }
}
